
package Playlist_Management;

/**
 *
 * @author GeorgeD
 */

import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import Main_menu.MainMenu;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import Radiostation_POJOS.Playlist;
import Radiostation_POJOS.Song;
import Radiostation_POJOS.PlaylistSongs;
import java.io.File;
import java.io.IOException;
import javax.persistence.NoResultException;


public class PlayListArchive extends javax.swing.JFrame {
            
    private MainMenu mainMenu;
    private PlayListManagementForm newPlaylistForm;
    private PlayListXML playlistXMLManager;    
    private List<Song> selectedPlaylistSongs;  
    
    public PlayListArchive() {
        initComponents();
        this.Radiostation_ProjectPUEntityManager.getTransaction().begin();
        this.PlayListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setLocationRelativeTo(null);//για την εμφάνιση του παραθύρου στο κέντρο        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        Radiostation_ProjectPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("Radiostation_ProjectPU").createEntityManager();
        query1 = java.beans.Beans.isDesignTime() ? null : Radiostation_ProjectPUEntityManager.createQuery("select p from Playlist p");
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        playlist1 = new Radiostation_POJOS.Playlist();
        jScrollPane1 = new javax.swing.JScrollPane();
        PlayListTable = new javax.swing.JTable();
        CreatePlayListBtn = new javax.swing.JButton();
        EditPlayListBtn = new javax.swing.JButton();
        ExitBtn = new javax.swing.JButton();
        ErrorMessage = new javax.swing.JLabel();
        DeletePlayListBtn = new javax.swing.JButton();
        SavePlayListBtn = new javax.swing.JButton();
        SaveXMLPlayListBtn = new javax.swing.JButton();
        ImportXMLPlayListBtn = new javax.swing.JButton();
        txt_xmlfile = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Λίστες Τραγουδιών");
        setResizable(false);

        PlayListTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list1, PlayListTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${playlistId}"));
        columnBinding.setColumnName("ID");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("ΟΝΟΜΑ ΛΙΣΤΑΣ");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(PlayListTable);

        CreatePlayListBtn.setText("Δημιουργία");
        CreatePlayListBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreatePlayListBtnActionPerformed(evt);
            }
        });

        EditPlayListBtn.setText("Ενημέρωση");
        EditPlayListBtn.setMaximumSize(new java.awt.Dimension(94, 26));
        EditPlayListBtn.setMinimumSize(new java.awt.Dimension(94, 26));
        EditPlayListBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditPlayListBtnActionPerformed(evt);
            }
        });

        ExitBtn.setText("Έξοδος");
        ExitBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitBtnActionPerformed(evt);
            }
        });

        ErrorMessage.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        ErrorMessage.setForeground(new java.awt.Color(255, 0, 0));
        ErrorMessage.setToolTipText("");

        DeletePlayListBtn.setText("Διαγραφή");
        DeletePlayListBtn.setBorder(EditPlayListBtn.getBorder());
        DeletePlayListBtn.setMaximumSize(new java.awt.Dimension(96, 26));
        DeletePlayListBtn.setMinimumSize(new java.awt.Dimension(96, 26));
        DeletePlayListBtn.setPreferredSize(new java.awt.Dimension(96, 26));
        DeletePlayListBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeletePlayListBtnActionPerformed(evt);
            }
        });

        SavePlayListBtn.setBorder(EditPlayListBtn.getBorder());
        SavePlayListBtn.setLabel("Αποθήκευση");
        SavePlayListBtn.setMaximumSize(new java.awt.Dimension(96, 26));
        SavePlayListBtn.setMinimumSize(new java.awt.Dimension(96, 26));
        SavePlayListBtn.setPreferredSize(new java.awt.Dimension(96, 26));
        SavePlayListBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SavePlayListBtnActionPerformed(evt);
            }
        });

        SaveXMLPlayListBtn.setText("Εξαγωγή Λίστας σε XML");
        SaveXMLPlayListBtn.setToolTipText("");
        SaveXMLPlayListBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveXMLPlayListBtnActionPerformed(evt);
            }
        });

        ImportXMLPlayListBtn.setText("Εισαγωγή Λίστας από αρχείο XML");
        ImportXMLPlayListBtn.setToolTipText("");
        ImportXMLPlayListBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ImportXMLPlayListBtnActionPerformed(evt);
            }
        });

        txt_xmlfile.setToolTipText("");

        jLabel1.setText("Αρχείο XML:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ErrorMessage, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(CreatePlayListBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(EditPlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(DeletePlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(SavePlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ExitBtn))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(2, 2, 2)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(SaveXMLPlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(ImportXMLPlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(txt_xmlfile))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CreatePlayListBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(EditPlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(DeletePlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ExitBtn)
                    .addComponent(SavePlayListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_xmlfile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(SaveXMLPlayListBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ImportXMLPlayListBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ErrorMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CreatePlayListBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreatePlayListBtnActionPerformed
        this.playlist1 = new Playlist();
        this.list1.add(playlist1);
        this.newPlaylistForm = new PlayListManagementForm(this, playlist1);
        this.newPlaylistForm.setVisible(true);
        this.setEnabled(false);
    }//GEN-LAST:event_CreatePlayListBtnActionPerformed

    private void ExitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitBtnActionPerformed
        new MainMenu().setVisible(true);
        dispose();
    }//GEN-LAST:event_ExitBtnActionPerformed

    private void EditPlayListBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditPlayListBtnActionPerformed
        ErrorMessage.setText("");
        int selectedRow = -1;//αρχικοποίηση μεταβλητής για να μην περιέχει προηγούμενη τιμή επιλογής.
        selectedRow = PlayListTable.getSelectedRow();
        if (selectedRow != -1){
            this.playlist1 = list1.get(PlayListTable.convertRowIndexToModel(selectedRow));
            this.newPlaylistForm = new PlayListManagementForm(this, playlist1);
            this.newPlaylistForm.setVisible(true);
            this.setEnabled(false);
        }
        else
            //Μήνυμα για την περίπτωση που δεν επιλεχθεί κάποια Λίστα.
            ErrorMessage.setText("Παρακαλώ επιλέξτε μία Λίστα από τον παραπάνω πίνακα");
    }//GEN-LAST:event_EditPlayListBtnActionPerformed

    private void DeletePlayListBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeletePlayListBtnActionPerformed
        // TODO add your handling code here:
        ErrorMessage.setText("");
        int index = PlayListTable.getSelectedRow();
        if(index >= 0){
            Playlist p = list1.get(PlayListTable.convertRowIndexToModel(index));
            List<PlaylistSongs> playlistSongs = p.getPlaylistSongList();            
            for(PlaylistSongs playlistSong:playlistSongs){
                Radiostation_ProjectPUEntityManager.remove(playlistSong);
            }            
            list1.remove(p);
            Radiostation_ProjectPUEntityManager.remove(p);
        } else {            
            ErrorMessage.setText("Παρακαλώ επιλέξτε μία Λίστα από τον παραπάνω πίνακα");
        }
    }//GEN-LAST:event_DeletePlayListBtnActionPerformed

    private void SavePlayListBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SavePlayListBtnActionPerformed
        // TODO add your handling code here:
        this.Radiostation_ProjectPUEntityManager.getTransaction().commit();
        new MainMenu().setVisible(true);
        dispose();
    }//GEN-LAST:event_SavePlayListBtnActionPerformed

    private void SaveXMLPlayListBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveXMLPlayListBtnActionPerformed
        // TODO add your handling code here:
        ErrorMessage.setText("");
        int index = PlayListTable.getSelectedRow();
        if(index >= 0){
            this.playlist1 = list1.get(PlayListTable.convertRowIndexToModel(index));            
            try{
                selectedPlaylistSongs = this.Radiostation_ProjectPUEntityManager
                        .createQuery("select s from Song s "
                        + "join s.playlistSongList pl_s "
                        + "join pl_s.playlist pl "
                        + "where pl.playlistId=" + this.playlist1.getPlaylistId())
                        .getResultList();

                playlistXMLManager = new PlayListXML(this.Radiostation_ProjectPUEntityManager);
                playlistXMLManager.setUsedForExport(true);                
                XMLReadWrite();
            } catch(NoResultException e){
                ErrorMessage.setText("'Εχετε επιλέξει κενή Λίστα");
            }
        } else {
            ErrorMessage.setText("Παρακαλώ επιλέξτε μία Λίστα από τον παραπάνω πίνακα");
        }
    }//GEN-LAST:event_SaveXMLPlayListBtnActionPerformed

    private void ImportXMLPlayListBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImportXMLPlayListBtnActionPerformed
        // TODO add your handling code here:
        playlistXMLManager = new PlayListXML(this.Radiostation_ProjectPUEntityManager);
        playlistXMLManager.setUsedForExport(false);
        XMLReadWrite();
    }//GEN-LAST:event_ImportXMLPlayListBtnActionPerformed

    private void XMLReadWrite(){
        ErrorMessage.setText("");
        String filepath = this.txt_xmlfile.getText().trim();
                PlayListXML playlistXMLManager = this.getPlaylistXMLManager();
                if( filepath != null && !filepath.equalsIgnoreCase("") ){
                    if( playlistXMLManager.isUsedForExport() ){
                        try {
                            File file = new File(filepath);
                            file.createNewFile();
                            playlistXMLManager.writeXML(file, this.getPlaylist1(), this.getSelectedPlaylistSongs());
                            //ErrorMessage.setText("Η εξαγωγή της επιλεγμένης Λίστας στο αρχείο XML ολοκληρώθηκε επιτυχώς");                    
                            JOptionPane.showMessageDialog(this, "Η εξαγωγή της επιλεγμένης Λίστας στο αρχείο XML ολοκληρώθηκε επιτυχώς");
                        } catch (IOException e) {                    
                            ErrorMessage.setText("Πρόβλημα κατά την δημιουργία του XML αρχείου");                    
                        }
                    } else {
                        try {
                            File file = new File(filepath);
                            if( file.createNewFile() ){
                                throw new IOException();
                            }

                            String msg = playlistXMLManager.readXml(file);
                            if( msg == null ){
                                //ErrorMessage.setText("Η εισαγωγή της Λίστας από το επιλεγμένο αρχείο XML ολοκληρώθηκε επιτυχώς");                    
                                JOptionPane.showMessageDialog(this, "Η εισαγωγή της Λίστας από το επιλεγμένο αρχείο XML ολοκληρώθηκε επιτυχώς");
                                this.setEnabled(true);
                                this.getList1().clear();
                                this.getList1().addAll(this.getQuery1().getResultList());                                
                            } else {                                
                                ErrorMessage.setText("Πρόβλημα κατά την επεγεργασία του αρχείου. Error: " + msg);                    
                            }                    
                        } catch (IOException e) {
                            ErrorMessage.setText("Δεν βρέθηκε αρχείο");
                        }
                    }
                } else {
                    ErrorMessage.setText("Παρακαλώ δηλώστε το επιθυμητό XML αρχείο");
                }
    }
    
    public Playlist getPlaylist1() {
        return playlist1;
    }

    public EntityManager getEntityManager1() {
        return Radiostation_ProjectPUEntityManager;
    }

    public List<Playlist> getList1() {
        return list1;
    }

    public PlayListXML getPlaylistXMLManager() {
        return playlistXMLManager;
    }

    public List<Song> getSelectedPlaylistSongs() {
        return selectedPlaylistSongs;
    }

    public Query getQuery1() {
        return query1;
    }
    
    /**
     * @param args the command line arguments
     */
    
//   *********** ΚΑΠΟΙΟΣ ΝΑ ΔΕΙ ΤΑ ΚΑΤΩΘΙ ΑΝ ΧΡΕΙΑΖΟΝΤΑΙ ΑΛΛΑΓΕΣ ***********
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CreatePlayListBtn;
    private javax.swing.JButton DeletePlayListBtn;
    private javax.swing.JButton EditPlayListBtn;
    private javax.swing.JLabel ErrorMessage;
    private javax.swing.JButton ExitBtn;
    private javax.swing.JButton ImportXMLPlayListBtn;
    private javax.swing.JTable PlayListTable;
    private javax.persistence.EntityManager Radiostation_ProjectPUEntityManager;
    private javax.swing.JButton SavePlayListBtn;
    private javax.swing.JButton SaveXMLPlayListBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<Radiostation_POJOS.Playlist> list1;
    private Radiostation_POJOS.Playlist playlist1;
    private javax.persistence.Query query1;
    private javax.swing.JTextField txt_xmlfile;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
